package com.work.count.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author ex_renbaokun
 */
public class FileUploadAndFileDownload {
    public static String upload(MultipartFile file, String filePath, boolean isUUID){
        //获取文件的原始文件名
        String fileOldName = file.getOriginalFilename();
        //设置新的文件名
        String fileName;
        //如果需要防重复，拼接uuid
        if (isUUID){
            fileName = filePath+ UUID.randomUUID()+fileOldName;
        }else {
            fileName = filePath + fileOldName;
        }
        //加入文件
        File dest = new File(fileName);
        //如果文件在不存在 则创建
        /*if (!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }*/
        try {
            //文件上传
            file.transferTo(dest);
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }
    public static boolean download(HttpServletResponse response, String fileName, String newName){
        File file = new File(fileName);
        try {
            //将文件放入输入流
            FileInputStream fis = new FileInputStream(file);
            //设置下载头信息，newName为文件的新下载名。
            response.setContentType("application/force-download");
            response.addHeader("Content-disposition", "attachment;fileName=" + newName);
            //获取response的输出流
            ServletOutputStream os = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            //文件传输
            while ((len = fis.read(bytes)) != -1){
                os.write(bytes,0,len);
            }
            //关闭流
            fis.close();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

}
